<template>
  <el-dialog
    :model-value="visible"
    :title="isEdit ? '编辑场景' : '新建场景'"
    width="90%"
    :before-close="handleClose"
    @update:model-value="$emit('update:visible', $event)"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="120px"
      class="scenario-form"
    >
      <!-- 基本信息 -->
      <el-card class="form-section">
        <template #header>
          <span class="section-title">基本信息</span>
        </template>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="场景名称" prop="name">
              <el-input v-model="formData.name" placeholder="请输入场景名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-select v-model="formData.status">
                <el-option label="草稿" value="draft" />
                <el-option label="就绪" value="ready" />
                <el-option label="运行中" value="running" />
                <el-option label="已完成" value="completed" />
                <el-option label="失败" value="failed" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="场景描述">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入场景描述"
          />
        </el-form-item>
      </el-card>

      <!-- 执行配置 -->
      <el-card class="form-section">
        <template #header>
          <span class="section-title">执行配置</span>
        </template>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="超时时间(秒)" prop="timeout">
              <el-input-number
                v-model="formData.timeout"
                :min="1"
                :max="3600"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="重试次数" prop="retry_count">
              <el-input-number
                v-model="formData.retry_count"
                :min="0"
                :max="5"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="并行执行">
              <el-switch v-model="formData.parallel_execution" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <!-- 环境变量 -->
      <el-card class="form-section">
        <template #header>
          <span class="section-title">环境变量</span>
        </template>

        <div class="key-value-editor">
          <div
            v-for="(variable, index) in environmentVariableList"
            :key="index"
            class="key-value-row"
          >
            <el-input
              v-model="variable.key"
              placeholder="变量名"
              style="width: 40%"
            />
            <el-input
              v-model="variable.value"
              placeholder="变量值"
              style="width: 40%; margin-left: 10px"
            />
            <el-button
              type="danger"
              size="small"
              style="margin-left: 10px"
              @click="removeEnvironmentVariable(index)"
            >
              删除
            </el-button>
          </div>
          <el-button size="small" @click="addEnvironmentVariable">
            <el-icon><Plus /></el-icon>
            添加环境变量
          </el-button>
        </div>
      </el-card>

      <!-- 执行配置 -->
      <el-card class="form-section">
        <template #header>
          <span class="section-title">执行配置</span>
        </template>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="超时时间(秒)">
              <el-input-number 
                v-model="formData.timeout" 
                :min="1" 
                :max="3600" 
                placeholder="30"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="重试次数">
              <el-input-number 
                v-model="formData.retry_count" 
                :min="0" 
                :max="10" 
                placeholder="0"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="并行执行">
              <el-switch v-model="formData.parallel_execution" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </div>
    </template>


  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, onMounted } from 'vue'
import { useToast } from 'vue-toastification'
import { apiAutomationApi } from '@/api/apiAutomation'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  scenarioData: {
    type: Object,
    default: null
  },
  isEdit: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:visible', 'confirm'])

const toast = useToast()
const formRef = ref()

// 表单数据
const formData = reactive({
  name: '',
  description: '',
  status: 'draft',
  timeout: 30,
  retry_count: 0,
  parallel_execution: false,
  environment_variables: {}
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入场景名称', trigger: 'blur' },
    { max: 200, message: '场景名称不能超过200个字符', trigger: 'blur' }
  ],
  timeout: [
    { required: true, message: '请输入超时时间', trigger: 'blur' }
  ],
  retry_count: [
    { required: true, message: '请输入重试次数', trigger: 'blur' }
  ]
}

// 环境变量列表
const environmentVariableList = ref([])

// 提交状态
const submitLoading = ref(false)

// 监听对话框显示状态
watch(() => props.visible, (newVal) => {
  if (newVal) {
    initFormData()
  }
})

// 初始化表单数据
const initFormData = () => {
  if (props.isEdit && props.scenarioData) {
    Object.assign(formData, {
      ...props.scenarioData,
      environment_variables: props.scenarioData.environment_variables || {}
    })
  } else {
    // 重置表单
    Object.assign(formData, {
      name: '',
      description: '',
      status: 'draft',
      timeout: 30,
      retry_count: 0,
      parallel_execution: false,
      environment_variables: {}
    })
  }

  // 初始化环境变量列表
  initEnvironmentVariableList()
}

// 初始化环境变量列表
const initEnvironmentVariableList = () => {
  environmentVariableList.value = Object.entries(formData.environment_variables || {}).map(([key, value]) => ({ key, value }))
  if (environmentVariableList.value.length === 0) {
    environmentVariableList.value.push({ key: '', value: '' })
  }
}



// 环境变量操作
const addEnvironmentVariable = () => {
  environmentVariableList.value.push({ key: '', value: '' })
}

const removeEnvironmentVariable = (index) => {
  environmentVariableList.value.splice(index, 1)
  if (environmentVariableList.value.length === 0) {
    environmentVariableList.value.push({ key: '', value: '' })
  }
}





// 处理表单提交
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    
    submitLoading.value = true

    // 处理环境变量
    const environment_variables = {}
    environmentVariableList.value.forEach(item => {
      if (item.key && item.value) {
        environment_variables[item.key] = item.value
      }
    })

    const submitData = {
      ...formData,
      environment_variables
    }

    let result
    if (props.isEdit) {
      result = await apiAutomationApi.updateScenario(props.scenarioData.id, submitData)
      toast.success('场景更新成功')
    } else {
      result = await apiAutomationApi.createScenario(submitData)
      toast.success('场景创建成功')
    }

    emit('confirm', result?.data || submitData)
    handleClose()
  } catch (error) {
    console.error('提交失败:', error)
  } finally {
    submitLoading.value = false
  }
}

// 关闭对话框
const handleClose = () => {
  emit('update:visible', false)
}

// 组件挂载时的初始化（已简化，不再需要加载接口列表）
onMounted(() => {
  // 场景基础信息编辑不需要加载接口列表
})
</script>

<style lang="scss" scoped>
.scenario-form {
  .form-section {
    margin-bottom: 20px;

    .section-title {
      font-weight: 600;
      color: #303133;
    }

    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }

  .key-value-editor {
    .key-value-row {
      display: flex;
      align-items: center;
      margin-bottom: 10px;
    }
  }


}

.dialog-footer {
  text-align: right;
}

:deep(.el-card__header) {
  padding: 12px 20px;
  background-color: #f8f9fa;
}

:deep(.el-card__body) {
  padding: 20px;
}
</style>